/**
 * 调试网络客户端 - 使用axios实现
 *
 * 使用方式：
 * 1. 复制此文件到您的项目中
 * 2. 安装axios: npm install axios
 * 3. 修改 serverUrl 为您的调试面板地址
 * 4. 在App中导入: import './utils/debugClient'
 * 5. 使用: global.$debug.info('Hello World')
 */

// 导入axios（确保项目已安装: npm install axios）
let axios
try {
  // React Native环境
  if (typeof require !== 'undefined') {
    axios = require('axios')
  } else {
    // 浏览器环境，需要全局加载axios
    axios = window.axios
  }
} catch (error) {
  console.error('❌ axios not found. Please install: npm install axios')
  axios = null
}

class DebugClient {
  constructor(config = {}) {
    this.config = {
      serverUrl: 'http://192.168.1.100:3000', // 修改为您的调试面板IP地址
      enabled: typeof __DEV__ !== 'undefined' ? __DEV__ : true, // 开发环境启用
      timeout: 8000, // 请求超时时间(增加到8秒)
      retryCount: 2, // 重试次数
      retryDelay: 1000, // 重试延迟
      ...config,
    }

    this._timers = new Map() // 用于time/timeEnd功能
    this._logQueue = [] // 日志队列
    this._isProcessing = false // 防止重复处理
    this._axiosInstance = null // axios实例

    if (this.config.enabled) {
      this._setupAxios()
      this._setupGlobalErrorHandler()
      this._startInitMessage()
    }
  }

  // 配置axios实例
  _setupAxios() {
    if (!axios) {
      console.warn('⚠️ axios未找到，调试功能将受限')
      return
    }

    this._axiosInstance = axios.create({
      baseURL: this.config.serverUrl,
      timeout: this.config.timeout,
      headers: {
        'Content-Type': 'application/json',
      },
    })

    // 请求拦截器
    this._axiosInstance.interceptors.request.use(
      (config) => {
        // console.log('📡 Debug request:', config.url)
        return config
      },
      (error) => {
        console.warn('📡 Debug request error:', error.message)
        return Promise.reject(error)
      },
    )

    // 响应拦截器
    this._axiosInstance.interceptors.response.use(
      (response) => {
        // console.log('✅ Debug response:', response.status)
        return response
      },
      (error) => {
        console.warn('📡 Debug response error:', error.message)
        return Promise.reject(error)
      },
    )
  }

  /**
   * 发送日志到远程调试面板（使用axios）
   */
  async _sendLog(level, messages, retryCount = 0) {
    if (!this.config.enabled) return

    if (!this._axiosInstance) {
      console.warn('📡 Debug log failed: axios not available')
      return
    }

    try {
      const logData = {
        type: 'log',
        timestamp: Date.now().toString(),
        data: {
          id: Date.now() + Math.random(),
          timestamp: Date.now().toString(),
          level,
          message: messages.map((msg) => {
            if (typeof msg === 'object') {
              try {
                return JSON.stringify(msg, null, 2)
              } catch (e) {
                return '[Object]'
              }
            }
            return String(msg)
          }),
          environment: this._getEnvironment(),
          userAgent: this._getUserAgent(),
        },
      }

      await this._axiosInstance.post('/api/log', logData)
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || 'Unknown error'

      // 重试机制
      if (retryCount < this.config.retryCount) {
        console.warn(`📡 Debug log failed, retrying (${retryCount + 1}/${this.config.retryCount}):`, errorMsg)
        setTimeout(() => {
          this._sendLog(level, messages, retryCount + 1)
        }, this.config.retryDelay * (retryCount + 1))
      } else {
        console.warn('📡 Debug log failed22:', errorMsg)
      }
    }
  }

  /**
   * 发送网络日志（使用axios）
   */
  async _sendNetworkLog(data, retryCount = 0) {
    if (!this.config.enabled || !this._axiosInstance) return

    try {
      const networkData = {
        type: 'network',
        timestamp: Date.now().toString(),
        data: {
          ...data,
          id: Date.now() + Math.random(),
          timestamp: Date.now().toString(),
        },
      }

      await this._axiosInstance.post('/api/log', networkData)
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || 'Unknown error'

      if (retryCount < this.config.retryCount) {
        setTimeout(() => {
          this._sendNetworkLog(data, retryCount + 1)
        }, this.config.retryDelay * (retryCount + 1))
      } else {
        console.warn('📡 Network log failed:', errorMsg)
      }
    }
  }

  // 基础日志方法
  debug(...messages) {
    return this._sendLog('debug', messages)
  }
  info(...messages) {
    return this._sendLog('info', messages)
  }
  log(...messages) {
    return this._sendLog('log', messages)
  }
  warn(...messages) {
    return this._sendLog('warn', messages)
  }
  error(...messages) {
    return this._sendLog('error', messages)
  }

  // 业务场景方法
  userAction(action, details) {
    return this.info(`👤 ${action}`, {
      action,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  pageEvent(page, event, extra) {
    return this.info(`📱 ${page} - ${event}`, {
      page,
      event,
      extra,
      timestamp: new Date().toISOString(),
    })
  }

  networkLog(method, url, requestData, responseData, duration) {
    return this._sendNetworkLog({
      method,
      url,
      requestData,
      responseData,
      duration,
      timestamp: new Date().toISOString(),
    })
  }

  errorLog(error, context) {
    return this.error('💥 Error:', {
      message: error.message,
      stack: error.stack,
      context,
      timestamp: new Date().toISOString(),
    })
  }

  performanceLog(action, duration, details) {
    return this.info(`⚡ Performance: ${action}`, {
      action,
      duration,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  table(data, title) {
    return this.info(`📊 Table: ${title || 'Data'}`, {
      data,
      title,
      timestamp: new Date().toISOString(),
    })
  }

  time(label) {
    this._timers = this._timers || new Map()
    this._timers.set(label, Date.now())
    return this.debug(`⏱️ Timer started: ${label}`)
  }

  timeEnd(label) {
    this._timers = this._timers || new Map()
    const startTime = this._timers.get(label)

    if (startTime) {
      const duration = Date.now() - startTime
      this._timers.delete(label)
      return this.info(`⏱️ Timer ended: ${label}`, {
        label,
        duration,
        timestamp: new Date().toISOString(),
      })
    } else {
      return this.warn(`⏱️ Timer not found: ${label}`)
    }
  }

  // 清空远程日志
  async clear() {
    if (!this.config.enabled || !this._axiosInstance) return

    try {
      await this._axiosInstance.post('/api/log', {
        type: 'clear',
        timestamp: Date.now().toString(),
        data: { action: 'clear' },
      })

      console.log('🧹 Remote logs cleared')
    } catch (error) {
      console.warn('Failed to clear remote logs:', error.message)
    }
  }

  // 测试连接
  async testConnection() {
    if (!this.config.enabled || !this._axiosInstance) return false

    try {
      await this._axiosInstance.post('/api/log', {
        type: 'log',
        data: {
          timestamp: Date.now().toString(),
          level: 'info',
          message: ['🔗 Debug connection test'],
        },
      })

      console.log('✅ Debug connection successful')
      return true
    } catch (error) {
      console.warn('❌ Debug connection failed:', error.message)
      return false
    }
  }

  // 更新配置
  updateConfig(newConfig) {
    this.config = { ...this.config, ...newConfig }

    if (this.config.enabled) {
      console.log('🔧 DebugClient config updated:', this.config)
      this._setupAxios() // 重新配置axios
    }
  }

  // 获取配置信息
  getConfig() {
    return {
      ...this.config,
      serverUrl: this.config.serverUrl,
      environment: this._getEnvironment(),
      userAgent: this._getUserAgent(),
    }
  }

  // 环境检测
  _getEnvironment() {
    if (typeof window !== 'undefined') {
      return 'browser'
    } else if (typeof global !== 'undefined' && global.navigator?.product === 'ReactNative') {
      return 'react-native'
    } else if (typeof process !== 'undefined' && process.versions?.node) {
      return 'node'
    }
    return 'unknown'
  }

  // 获取用户代理
  _getUserAgent() {
    if (typeof navigator !== 'undefined') {
      return navigator.userAgent
    }
    return 'Unknown'
  }

  // 全局错误处理
  _setupGlobalErrorHandler() {
    const originalConsoleError = console.error
    console.error = (...args) => {
      originalConsoleError.apply(console, args)
      this.error('Console Error:', ...args)
    }

    // React Native和浏览器的全局错误捕获
    if (typeof window !== 'undefined') {
      window.addEventListener('error', (event) => {
        this.errorLog(new Error(event.message), 'Window Error')
      })

      window.addEventListener('unhandledrejection', (event) => {
        this.errorLog(new Error(event.reason), 'Unhandled Promise Rejection')
      })
    }
  }

  // 初始化消息
  _startInitMessage() {
    setTimeout(() => {
      if (this.config.enabled) {
        console.log('🚀 DebugClient initialized:', this.config.serverUrl)
        this.info('🚀 DebugClient ready', {
          environment: this._getEnvironment(),
          serverUrl: this.config.serverUrl,
        })
      }
    }, 100)
  }
}

// 创建全局实例
const $debug = new DebugClient()

// 挂载到全局
if (typeof global !== 'undefined') {
  global.$debug = $debug
}
if (typeof window !== 'undefined') {
  window.$debug = $debug
}

// 导出(如果支持模块化)
if (typeof module !== 'undefined' && module.exports) {
  module.exports = $debug
}
